import React from 'react';
import classNames from 'classnames';
import { getLocale } from 'umi';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import customEditor from './_assets/ckeditor';
import './_assets/translations/zh-cn';
import './_assets/translations/ja';
import styles from './index.less';

/**
 * https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/react.html
 * https://ckeditor.com/docs/ckeditor5/latest/features/image-upload/base64-upload-adapter.html
 * https://ckeditor.com/ckeditor-5/online-builder
 * https://github.com/ckeditor/ckeditor5-build-classic
 */
const Index = (props) => {
  const { value, onChange, disabled, id, config, className, style, ...rest } = props;

  const locale = getLocale();
  const language = locale.includes('-') ? locale.match(/(?<=^).*?(?=-)/g)?.[0] : locale;

  return (
    <span id={id} className={classNames(styles.wrapper, className)} style={style}>
      {(disabled && disabled.render && disabled.render(value)) || (
        <CKEditor
          disabled={!!disabled}
          id={id}
          config={{
            language: language === 'zh' ? 'zh-cn' : language,
            toolbar: {
              items: [
                'undo',
                'redo',
                'removeFormat',
                '|',
                'heading',
                'fontSize',
                '|',
                'bold',
                'italic',
                'strikethrough',
                'underline',
                'subscript',
                'superscript',
                'code',
                'codeBlock',
                '|',
                'fontColor',
                'fontBackgroundColor',
                '|',
                'alignment',
                '|',
                'bulletedList',
                'numberedList',
                'indent',
                'outdent',
                '|',
                'link',
                'blockQuote',
                'horizontalLine',
                'pageBreak',
                '|',
                'imageUpload',
                'insertTable',
                'mediaEmbed',
              ],
            },
            fontSize: {
              options: [12, 13, 14, 15, 16, 19, 22, 24, 29, 32, 40, 48],
            },
            image: {
              toolbar: ['imageTextAlternative', 'imageStyle:full', 'imageStyle:side', 'linkImage'],
            },
            table: {
              contentToolbar: [
                'tableColumn',
                'tableRow',
                'mergeTableCells',
                'tableCellProperties',
                'tableProperties',
              ],
            },
            ...config,
          }}
          {...rest}
          editor={customEditor}
          data={value}
          onChange={(event, editor) => {
            if (onChange) {
              onChange(editor.getData());
            }
          }}
        />
      )}
    </span>
  );
};

export default Index;
